<script setup lang="ts">
import { ref, toRaw } from "vue";
import { onLoad, onUnload } from "@dcloudio/uni-app";
import { items_api, del_api } from "@/package/my/api/member_address";
import { EV_ADDRESS } from "@/constant/event";
import { strReplaceByLen } from "@/utils/string";
import { Router } from "@/utils/router";
import { Toast } from "@/utils/toast";

import ListEmpty from "@/components/list/empty.vue";
import FormCheckbox from "@/components/form/checkbox.vue";
import ListAddressItem from "./components/list-address-item.vue";
import FormButton from "@/components/form/button.vue";
import PopupModal from "@/components/popup/modal.vue";

onLoad((options) => {
  reloadList();

  if (options?.type === "select") {
    // 选择地址
    uni.setNavigationBarTitle({ title: "选择地址" });
    listType.value = "select";
    selectId.value = options?.id || "";
  }

  uni.$on(EV_ADDRESS, addressCallback);
});
onUnload(() => uni.$off(EV_ADDRESS, addressCallback));

const selectId = ref("");
const listType = ref<"select" | "">("");
const listData = ref<any[]>([]);
const listStatus = ref<"more" | "loading" | "noMore">("more");
const reloadList = () => {
  return items_api().then((resp) => {
    listData.value = resp.items.map((i) => {
      return {
        ...i,
        phone_str: strReplaceByLen(i.phone),
      };
    });
    listStatus.value = "noMore";
  });
};
const addressClick = (index: number) => {
  const item = listData.value[index];
  if (listType.value !== "select") return editClick(item.id);
  selectId.value = item.id;
  uni.$emit(EV_ADDRESS, { type: "select", data: toRaw(item) });
  Router.navigateBack();
};
const editClick = (id?: string) => {
  Router.navigateTo(`/package/my/pages/address/edit?id=${id || ""}`);
};
const delClick = (id: string) => {
  popupModal.value?.show({ content: "是否确定删除该信息？" }, () => {
    Toast.showLoading();
    del_api({ id })
      .then(() => {
        Toast.hideLoading();
        // showToast("删除成功");
        reloadList();
      })
      .catch(() => Toast.hideLoading());
  });
};

const addressCallback = (e: { type: "edit" | "del" }) => {
  console.info(`触发事件：${EV_ADDRESS}`, e);
  (e.type === "edit" || e.type === "del") && reloadList();
};

const popupModal = ref<InstanceType<typeof PopupModal>>();
</script>

<template>
  <view
    class="list-no-data"
    v-if="listData.length === 0 && listStatus === 'noMore'"
  >
    <ListEmpty text="您还没有收货地址～" />
  </view>
  <view class="list-data" v-else>
    <uni-swipe-action>
      <view class="list-data-action" v-for="(i, d) of listData" :key="i.id">
        <uni-swipe-action-item>
          <view class="list-data-item" @click="addressClick(d)">
            <view class="list-data-checkbox" v-if="listType === 'select'">
              <FormCheckbox :modelValue="selectId === i.id" />
            </view>
            <view style="flex-grow: 1; min-width: 0">
              <ListAddressItem :info="i">
                <image
                  class="list-data-edit"
                  src="@/package/my/static/address-edit.png"
                  @click.stop="editClick(i.id)"
                />
              </ListAddressItem>
            </view>
          </view>
          <template v-slot:right>
            <view class="list-data-del" @click="delClick(i.id)">删除</view>
          </template>
        </uni-swipe-action-item>
      </view>
    </uni-swipe-action>
  </view>

  <view class="list-fixed">
    <view @click="editClick('')">
      <FormButton>新增地址</FormButton>
    </view>
  </view>

  <PopupModal ref="popupModal" />
</template>

<style lang="scss">
.list-data {
  padding-top: 30rpx;
  padding-bottom: 120rpx;

  .list-data-action {
    margin-bottom: 20rpx;
  }

  .list-data-item {
    display: flex;
    align-items: center;
    padding-left: 30rpx;
    padding-right: 30rpx;
  }

  .list-data-checkbox {
    flex-shrink: 0;
    margin-right: 20rpx;
  }

  .list-data-edit {
    flex-shrink: 0;
    width: 50rpx;
    height: 50rpx;
    margin-left: 20rpx;
  }

  .list-data-del {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100rpx;
    height: 100%;
    margin-right: 20rpx;
    font-size: 28rpx;
    color: #ffffff;
    border-radius: 10rpx;
    background-color: #ff4d42;
  }
}

.list-no-data {
  height: calc(100vh - env(safe-area-inset-bottom));
}

.list-fixed {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: 106rpx;
  padding: 14rpx 60rpx env(safe-area-inset-bottom);
  background-color: #ffffff;
}
</style>